package com.maycurobj.controller.maycur;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maycurobj.domain.maycurDTO.MaycurCustomerDTO;
import com.maycurobj.pojo.AnnualBudget;
import com.maycurobj.pojo.MayCurOutVoucher;
import com.maycurobj.service.http.HttpAPIService;
import com.maycurobj.service.impl.CrmSerivceImpl;
import com.maycurobj.service.impl.MaycurService;
import com.maycurobj.service.impl.OutVoucherService;
import com.maycurobj.util.NormalUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 每刻外部关联单据 接口
 * --OA流程
 */
@Controller
@RequestMapping("/maycur/outside")
@Slf4j
public class MaycurOutVoucherController {

    @Autowired
    private MaycurService maycurService;

    @Autowired
    private HttpAPIService httpAPIService;

    @Autowired
    private OutVoucherService voucherService;

    @Autowired
    private CrmSerivceImpl crmSerivce;

//    @Value("${synccp.url}")
//    private String cpurl;

    /**
     * 接受每刻获取外部流程字段请求
     */
    @PostMapping("/getWorkflowInfoTest")
    @ResponseBody
    public Map<String, Object> pushTest(@RequestBody Map<String, Object> voucher) {
        Map<String, Object> returnMap = new HashMap<>();
        log.info("测试----获取每刻关联外部单据请求：{}", JSONObject.toJSONString(voucher));
        //返回(测试)
        JSONObject jsonDataList = new JSONObject();
        jsonDataList.put("formName", "外部单据事由");
        jsonDataList.put("formDataCode", "00001");
        jsonDataList.put("submitData", NormalUtil.nowDateToLong());
        jsonDataList.put("submitUser", "痞子姚");
        jsonDataList.put("url", "http://www.baidu.com");
        JSONArray jsonDataLists = new JSONArray();
        jsonDataLists.add(jsonDataList);
        JSONObject data = new JSONObject();
        data.put("recordsTotal", jsonDataLists.size());
        data.put("dataList", jsonDataLists);

        returnMap.put("errorMsg", "success");
        returnMap.put("success", true);
        returnMap.put("data", data);

        return returnMap;
    }

    /**
     * 接受每刻获取Crm会议名称（数据互联）
     */
    @PostMapping("/getAnnualBudgetInfoTest")
    @ResponseBody
    public JSONObject AnnualBudgetpushTest(@RequestBody Map<String, Object> entity) {
        //获取每刻发送的请求体
//        Map<String, Object> returnMap = new HashMap<>(entity);
        log.info("测试----获取每刻Crm会议名称（数据互联）请求：{}", JSONObject.toJSONString(entity));
        //从请求体中挑出keyWord，获取用户输入的关键字。
        String key = entity.getOrDefault("keyWord","").toString();
        //包装需要的固定响应参数
        JSONObject data = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonBusinessCodeList = new JSONObject();
        jsonBusinessCodeList.put("label","bizCode");
        jsonBusinessCodeList.put("businessCode","bizCode");
        jsonBusinessCodeList.put("primary",false);
        jsonBusinessCodeList.put("display",false);
        jsonBusinessCodeList.put("type","SingleTextInput");
        JSONObject jsonlabelList = new JSONObject();
        jsonlabelList.put("primary",true);
        jsonlabelList.put("label","会议名称");
        jsonlabelList.put("type","SingleTextInput");
        jsonlabelList.put("businessCode","name");
        jsonlabelList.put("display",true);
        JSONObject jsonlabelnumberList = new JSONObject();
        jsonlabelnumberList.put("label","会议id");
        jsonlabelnumberList.put("primary",false);
        jsonlabelnumberList.put("type","SingleTextInput");
        jsonlabelnumberList.put("businessCode","code");
        jsonlabelnumberList.put("display",false);
        jsonArray.add(jsonBusinessCodeList);
        jsonArray.add(jsonlabelList);
        jsonArray.add(jsonlabelnumberList);
        //根据用户输入的关键字查询相匹配的会议，并插入dataList中
        JSONArray dataList = new JSONArray();
        List<AnnualBudget> lists=crmSerivce.getAnnualBudgetList(key);
        for (AnnualBudget tmp : lists) {
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("bizCode", tmp.getCampaignid());
            jsonObject1.put("name", tmp.getName());
            jsonObject1.put("code", tmp.getCampaignid());
            dataList.add(jsonObject1);
        }

        //把响应参数包装到data，为json格式。
        data.put("dataList", dataList);
        data.put("recordsTotal",crmSerivce.getAnnualBudgetList(key).size());
        data.put("isPage",true);
        data.put("definedList",jsonArray);
        JSONObject req = new JSONObject();
        req.put("data", data);
        req.put("success", true);
        req.put("errorMsg", "");
        //输出返回的json
        log.info("req info:{}", req.toJSONString());
        return req;
    }


    /**
     * 接受每刻获取外部流程字段请求
     */
    @PostMapping("/getWorkflowInfo")
    @ResponseBody
    public Map<String, Object> push(@RequestBody MayCurOutVoucher voucher) {
        try {
            Map<String, Object> returnMap = new HashMap<>();
            log.info("获取每刻关联外部单据请求：{}", JSONObject.toJSONString(voucher));

            if ("".equals(voucher.getVoucherCode())) {
                return null;
            }
            String employeeId = "";
            //如果是借款单的 特殊获取
            if ("FT2111271PQCOYDC".equals(voucher.getVoucherCode())) {
                employeeId = voucher.getLoanUser();
            } else {
                employeeId = voucher.getEmployeeId();
            }

            log.info("获取每刻关联外部单据类型：{},获取到的用户:{}", voucher.getVoucherCode(),employeeId);

            String maycurType = voucher.getVoucherCode();
            String keyWord = NormalUtil.null2String(voucher.getKeyWord());
            Integer pageSize = voucher.getLength();
            //取整
            Integer curPage = Integer.valueOf(voucher.getStart() / pageSize);
            //分页对象
            Pageable pageable = PageRequest.of(curPage, pageSize);
            Map<String, Object> _map = new HashMap<>();
            //service 处理
            //map方式
            Map<String, String> serviceMap = new HashMap<>();
            //物品领用
            serviceMap.put("FT2112041IRBMKG0", "getHeTongWF");
            //合同(对公付款 非供应链)
            serviceMap.put("FT21102113QWJ3EO", "getHeTongWF");
            //借款
            serviceMap.put("FT2111271PQCOYDC", "getJieKuanWF");
            //一般报销
            serviceMap.put("FT211022144CQR5S", "getYiBanWF");
            //合同 对公付款(供应链)
            serviceMap.put("FT211226265UJQPS", "getHeTongWF");

            if (serviceMap.containsKey(maycurType)) {
                //包含
                String methodName = serviceMap.get(maycurType);
                try {
                    Method method = this.voucherService.getClass().getDeclaredMethod(methodName, String.class, String.class, Pageable.class);
                    _map = (Map<String, Object>) method.invoke(this.voucherService, employeeId, keyWord, pageable);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

            //普通方式
//        if ("FT2112041IRBMKG0".equals(maycurType)) {
//            //物品领用--暂时对应对公合同的流程(测试用)
//            _map = this.voucherService.getHeTongWF(employeeId, pageable);
//
//        } else if ("FT21102113QWJ3EO".equals(maycurType)) {
//            //合同
//            _map=this.voucherService.getHeTongWF(employeeId, pageable);
//
//        } else if ("FT2111271PQCOYDC".equals(maycurType)) {
//            //借款
//            _map=this.voucherService.getJieKuanWF(employeeId, pageable);
//
//        } else if ("FT211022144CQR5S".equals(maycurType)) {
//            //一般报销
//            _map=this.voucherService.getYiBanWF(employeeId, pageable);
//        }
            returnMap.put("errorMsg", "success");
            returnMap.put("success", true);
            returnMap.put("data", _map);
            log.info("---->>>打印外部流程报文{}", JSONObject.toJSONString(returnMap));
            return returnMap;
        } catch (Exception e) {
            e.printStackTrace();
            return errReturn();
        }
    }

    /**
     * 接受每刻外部自定义项的请求
     */
    @PostMapping("/getUserCustomerRequest")
    @ResponseBody
    public Map<String, Object> getUserCustomerRequest(@RequestBody MayCurOutVoucher entity) {
        log.info("请求到用户自定义客户档案请求------>>>{}", JSONObject.toJSONString(entity));
        JSONObject entityJson = JSONObject.parseObject( JSONObject.toJSONString(entity));
        //外部客户接口获取用户工号id 为空
        if (StringUtils.isBlank(entity.getEmployeeId())) {
            return errReturn();
        }
        //获取全局客户开关
        String employeeId = entity.getEmployeeId();
        Integer pageSize = entity.getLength();
        Integer currentPage = entity.getStart()/entity.getLength();
        String keyWord = entity.getKeyWord();
        Map<String, Object> retMap=crmSerivce.getCrmUserRoleCustomer(currentPage, pageSize, keyWord, employeeId);
        //整理结果
        //处理表头
        List<DefinedColList> colLists = getUserCustomerCol();
        retMap.put("definedList", colLists);
        retMap.put("isPage", true);
        Map<String, Object> responseJson = new HashMap<>();
        responseJson.put("data", retMap);
        responseJson.put("success", true);
        responseJson.put("errorMsg", "");
        log.info("打印下 每刻外部自定义项的返回报文---->>>{}", JSONObject.toJSONString(responseJson));
        return responseJson;
    }

    //获取是否内容
    @Deprecated
    private boolean getFlag(JSONObject jsonObject,String fieldName) {
        try {
            JSONObject _formData = jsonObject.getJSONObject("formData");
            JSONObject _objData = _formData.getJSONObject(fieldName);
            JSONObject __value = _objData.getJSONObject("value");
            if (__value.getString("text").equals("是")) {
                return true;
            }else{
                return false;
            }
        } catch (Exception e) {
            log.info("getFlag 转换异常");
            return false;
        }
    }

    private List<DefinedColList> getUserCustomerCol() {
        //id
        DefinedColList idCol = new DefinedColList();
        idCol.setLabel("CRMID");
        idCol.setDisplay(false);
        idCol.setBusinessCode("bizCode");
        idCol.setPrimary(true);
        idCol.setType("SingleTextInput");
        //name
        DefinedColList name = new DefinedColList();
        name.setLabel("名称");
        name.setEcho(true);
        name.setDisplay(true);
        name.setBusinessCode("name");
        name.setType("SingleTextInput");
        name.setPrimary(false);

        //u8code
        DefinedColList u8code = new DefinedColList();
        u8code.setLabel("ERP编码");
        u8code.setDisplay(true);
        u8code.setBusinessCode("u8Code");
        u8code.setType("SingleTextInput");

        List<DefinedColList> retList = new ArrayList<>();
        retList.add(idCol);
        retList.add(name);
        retList.add(u8code);
        return retList;
    }

    /**
     * 异常返回
     *
     * @return
     */
    private Map<String, Object> errReturn() {
        Map<String, Object> returnMap = new HashMap<>();
        JSONObject jsonDataList = new JSONObject();
        jsonDataList.put("formName", "每刻接口异常，此功能暂无法使用");
        jsonDataList.put("formDataCode", "00000");
        jsonDataList.put("submitData", NormalUtil.nowDateToLong());
        jsonDataList.put("submitUser", "管理员");
        jsonDataList.put("url", "");
        JSONArray jsonDataLists = new JSONArray();
        jsonDataLists.add(jsonDataList);
        JSONObject data = new JSONObject();
        data.put("recordsTotal", jsonDataLists.size());
        data.put("dataList", jsonDataLists);

        returnMap.put("errorMsg", "success");
        returnMap.put("success", true);
        returnMap.put("data", data);
        return returnMap;
    }
}

/**
 * 表头内部类
 */
@Data
class DefinedColList{
    private String businessCode;
    private boolean echo;
    private boolean display;
    private String label;
    private boolean primary;
    private String type;
}
